<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <span>本月: 社保在缴 公积金在缴</span>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 员工列表 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" sortable="">
            <template v-slot="{row}">
              {{ formHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formTime }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template #default="{row}">
              <el-switch v-model="row.enableState" :active-value="1" :inactive-value="2" active-color="#13ce66" inactive-color="#ff4949" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :page-sizes="[5, 10, 20, 30, 40, 50, 100]" :current-page="queryParams.page" :page-size="queryParams.size" :total="total" layout="sizes,prev, pager, next, ->, total" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
        </div>
      </el-card>
    </div>
    <AddEmployees :show-dialog.sync="showDialog" />
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees.js'
import types from '@/api/constant/employees'
import AddEmployees from './components//AddEmployees.vue'
import moment from 'moment'
// import { formatDate } from '@/utils'
export default {
  name: 'Employees',
  components: {
    AddEmployees
  },
  data () {
    return {
      // 开启弹窗
      showDialog: false,
      // 格式化 聘用形式
      hireType: types.hireType,
      // 列表总数
      total: 0,
      // 员工列表
      list: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10
      }
    }
  },
  created () {
    this.loadEmpList()
  },
  methods: {
    // 转化导出Excel需要的数据
    getExportData (list) {
      const obj = {
        title: [],
        data: []
      }
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 使用Object.keys()方法获取对象中所有的key,结果为按序排列的数组
      obj.title = Object.keys(headers)
      list.forEach(item => {
        const row = []
        for (const key in headers) {
          // 通过中文key 获得对应的英文key
          const name = headers[key]
          // 对后端数据进行取值，添加到数组，每个数组为一个员工的基本信息
          const value = item[name]
          if (['timeOfEntry', 'correctionTime'].includes(name)) {
            const time = moment(value).format('yyyy-MM-DD')
            row.push(time)
          } else if (name === 'formOfEmployment') {
            const isOk = this.hireType.find(item => item.id === Number(value))
            if (isOk) {
              row.push(isOk.value)
            } else {
              row.push('其他')
            }
          } else {
            row.push(value)
          }
        }
        obj.data.push(row)
      });
      return obj
    },
    // ====================  Excel导出功能
    async handleExport () {
      const ret = await reqGetEmployeeList({ page: 1, size: 15 })
      const list = this.getExportData(ret.data.rows)
      console.log(ret, list);
      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: list.title, // 表头 必填
      //     data: list.data, // 具体数据 必填
      //     filename: 'excel-list', // 非必填
      //     autoWidth: true, // 非必填
      //     bookType: 'xlsx' // 非必填
      //   })
      // })
    },
    // ====================  员工删除功能
    async handleDel (id) {
      const ret = await this.$confirm('确认要删除员工吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (ret === "cancel") return
      try {
        const ret = await reqDelEmployee(id)
        console.log(ret);
        if (ret.code === 10000) {
          // 删除成功 刷新列表
          this.loadEmpList()
          this.$message.success('删除员工成功')
        } else {
          this.$message.warning(ret.message)
        }
      } catch (error) {
        this.$message.error('删除员工失败')
      }
    },
    // ====================  格式化聘用形式
    formHireType (type) {
      const info = this.hireType.find(item => parseInt(item.id) === parseInt(type))
      if (info) {
        return info.value
      } else {
        return '其他'
      }
    },
    // 控制每页显示条数
    handleSizeChange (val) {
      this.queryParams.size = val
      this.loadEmpList()
    },
    // 切换分页
    handleCurrentChange (val) {
      this.queryParams.page = val
      this.loadEmpList()
    },
    // 加载员工列表数据
    async loadEmpList () {
      const ret = await reqGetEmployeeList(this.queryParams)
      if (ret.code === 10000) {
        this.list = ret.data.rows
        this.total = ret.data.total
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
